<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row class="query-form" >
        <Col span="8">
					<FormItem label="单位名称：" prop="order">
            <!--						<cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName'
                          @setOrgname='setQueryOrgName' :orgTree="true"></cascader-dom>-->
            <company-select v-model="form1.companyName" class="query-form-el"></company-select>
          </FormItem>
					</Col>
        <Col span="8">
          <FormItem label="二级集团：">
            <two-level-org class="query-form-el" v-model="form1.twoLevelOrgId"></two-level-org>
          </FormItem>
        </Col>

        <Col span="8" v-if="!switchFlag">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
        <Col span="8" v-else>
          <FormItem label="预案类别：" prop="emType">
            <Select v-model="form1.emType" multiple :max-tag-count="2" @on-change="selectEmType" class="query-form-el">
              <Option v-for="item in emTypeList" :value="item.codingCodeId"
                      :key="item.codingCodeId">{{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="应急计划：">
            <Select v-model="form1.fillIn" class="query-form-el">
              <Option value="1">已填报</Option>
              <Option value="2">未填报</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="事件类型：" prop="eventTypeId">
            <Select v-model="form1.eventTypeId" multiple :max-tag-count="2" @on-change="selectEventTypes"
                    class="query-form-el">
              <Option v-for="item in eventTypeList" :value="item.codingCodeId"
                      :key="item.codingCodeId">{{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="预案名称：" prop="emName">
            <Input class="query-form-el" type="text" v-model="form1.emName"></Input>
          </FormItem>
        </Col>
      </Row>

      <Row v-show="switchFlag" class="query-form">
        <Col span="8" offset="16">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <!--<Button size="large"  class="ivu-btn-delete" icon="md-trash" @click="batDelete">删除</Button>-->
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" size="small" :loading="loading" no-data-text="没有查询到相关数据!"
           @on-selection-change='getSelectRows'
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>
    <Modal title="应急预案" :transfer=false v-model="model1" :width=600>
      <Row>
        <Col span="24">
          <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="所属单位：" prop="companyId">
                  <cascaderDom  class="query-form-el" ref="groupOrg" style="width: 100%;"
                               @setOrgInfo='(data)=>{cascaderDomIdChangeHandle(data,"companyId");}'
                               @setOrgname='(data)=>{cascaderDomNameChangeHandle(data,"companyName");}'
                               :currentOrgId = "form1datacopy.companyId"
                               :setCurrentName="{label:form1datacopy.companyName, value:form1datacopy.companyId}"
                               :orgTree="true" ></cascaderDom>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="所属二级集团：" >
                  <Input type="text" v-model="form1datacopy.twoLevelOrgName" :readonly="true"></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="预案名称：" prop="emName">
                  <Input type="text" v-model="form1datacopy.emName"></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="备案：" prop="filing">
                  <Select v-model="form1datacopy.filing">
                    <Option value="1">是</Option>
                    <Option value="2">否</Option>
                  </Select>
                </FormItem>
              </Col>
<!--              <Col span="11">-->
<!--                <FormItem label="预案级别：" prop="emLevelId">-->
<!--                  <Select v-model="form1datacopy.emLevelId">-->
<!--                    <Option v-for="item in emLevelList" :value="item.codingCodeId"-->
<!--                            :key="item.codingCodeId">{{ item.codingName }}-->
<!--                    </Option>-->
<!--                  </Select>-->
<!--                </FormItem>-->
<!--              </Col>-->
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="事件类型：" prop="eventTypeId">
                  <Select v-model="form1datacopy.eventTypeId">
                    <Option v-for="item in eventTypeList" :value="item.codingCodeId"
                            :key="item.codingCodeId">{{ item.codingName }}
                    </Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="预案类别：" prop="emType">
                  <Select v-model="form1datacopy.emType">
                    <Option v-for="item in emTypeList" :value="item.codingCodeId"
                            :key="item.codingCodeId">{{ item.codingName }}
                    </Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="填报人：" prop="createUserName">
                  <Input type="text" v-model="form1datacopy.createUserName"></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填报人电话：" prop="phone">
                  <Input type="text" v-model="form1datacopy.phone"></Input>
                </FormItem>
              </Col>
            </Row>
<!--            <Row type="flex" justify="space-around" class="code-row-bg">-->
<!--              <Col span="11">-->
<!--                <FormItem label="备案：" prop="filing">-->
<!--                  <Select v-model="form1datacopy.filing">-->
<!--                    <Option value="1">是</Option>-->
<!--                    <Option value="2">否</Option>-->
<!--                  </Select>-->
<!--                </FormItem>-->
<!--              </Col>-->
<!--              <Col span="11">-->

<!--              </Col>-->
<!--            </Row>-->
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="备案情况：" prop="filingSituation">
                  <Input v-model="form1datacopy.filingSituation" type="textarea" :rows="2"/>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="备注：" prop="notes">
                  <Input v-model="form1datacopy.notes" type="textarea" :rows="2"/>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="预案文本：">
                  <div style="width: 100%">
                    <Upload ref="upload"
                            :before-upload="beforeUpload"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 20px">
                        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                      </div>
                    </Upload>
                  </div>

                  <div v-show="uploadList.length>0" v-for="(item,index) in uploadList" :key='item'>
                    <a @click="downloadFile(form1datacopy.emId,item,index)">{{ item.fileName }}</a>
                    <Button type="text" icon="md-trash" @click="remove1(item.id)"
                            style="margin-left: 5px;margin-bottom: 3px"/>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
              </Col>

            </Row>


          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="submit('form1datacopy')">
          确定
        </Button>
        <Button type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>
    <Modal title="应急预案详情" class="modal-view-detail" :transfer=false v-model="model2" :width=800>
      <Row>
        <Col span="24">
          <Form :model="form1datacopy" :label-width="160">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="所属单位：">
                  {{ form1datacopy.companyName }}
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="二级集团：">
                  {{ form1datacopy.twoLevelOrgName }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="预案名称：">
                  {{ form1datacopy.emName }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="备案：">
                  {{ form1datacopy.filing == "1" ? "是" : form1datacopy.filing == "2" ? "否" : "" }}
                </FormItem>
              </Col>
<!--              <Col span="11">-->
<!--                <FormItem label="预案级别：" >-->
<!--                  {{this.getCodingSortName(form1datacopy.emLevelId)}}-->
<!--                </FormItem>-->
<!--              </Col>-->
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="事件类型：" >
                  {{ this.getCodingSortName(form1datacopy.eventTypeId) }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="预案类别：" >
                  {{this.getCodingSortName(form1datacopy.emType)}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="填报人：">
                  {{ form1datacopy.createUserName }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填报人电话：">
                  {{ form1datacopy.phone }}
                </FormItem>
              </Col>
            </Row>
<!--            <Row type="flex" justify="space-around" class="code-row-bg">-->
<!-- -->
<!--              <Col span="11">-->

<!--              </Col>-->
<!--            </Row>-->
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="预案文本：">
                  <div v-show="uploadList.length>0" v-for="(item,index) in uploadList" :key='item'>
                    <a @click="downloadFile(form1datacopy.emId,item,index)">{{ item.fileName }}</a>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="备案情况：">
                  {{ form1datacopy.filingSituation }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="备注：" prop="notes ">
                  {{ form1datacopy.notes }}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '../../../../api'
import {sessionStorage} from '../../../../common/cacheUtils.js';

var cascaderDom = () => import('@/components/cascader-dom.vue');
export default {
  components:{
    cascaderDom
  },
  data() {
    return {
      currentUser:sessionStorage('userId').getObject('userId'),
      fileUrl: Api.interestedPartiesUserFile,
      emLevelList: [],
      eventTypeList: [],
      emTypeList: [],
      codingSortList: [],
      downloadUrl: Api.downloadPTWSchemeFile,
      esTypeList: [],
      upUrl: Api.uploadPTWSchemeFile,
      switchFlag: false,
      form1: {},
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      uploadListVisible:[],
      uploadListPercent:[],
      dataTable: [],
      uploadList: [],
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },

        {
          title: "应急计划",
          width: 130,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            let color = 'green';
            if (params.row.fillIn != '1'){
              color = 'red';
            }
            return h('span',{
              style: {
                color: color
              }
            }, params.row.fillIn == '1'?'已填报':'未填报');
          }
        },
        {
          title: '预案名称',
          align: 'center',
          minWidth: 200,
          key: 'emName',
        },
        {
          title: '所属单位',
          align: 'center',
          minWidth: 200,
          key: 'companyName',
        },
        {
          title: '所属二级集团',
          align: 'center',
          minWidth: 200,
          key: 'twoLevelOrgName',
        },
        // {
        //   title: '预案级别',
        //   width: 150,
        //   align: 'center',
        //   key: 'emLevelName',
        //   render: (h, params) => {
        //     return h('span', this.getCodingSortName(params.row.emLevelId));
        //   }
        // },
        {
          title: '事件类型',
          width: 150,
          align: 'center',
          key: 'eventTypeName',
          render: (h, params) => {
            return h('span', this.getCodingSortName(params.row.eventTypeId));
          }
        },
        {
          title: '预案类别',
          width: 150,
          align: 'center',
          key: 'emTypeName',
          render: (h, params) => {
            return h('span', this.getCodingSortName(params.row.emType));
          }
        },
        {
          title: '填报人',
          align: 'center',
          minWidth: 100,
          key: 'createUserName',
        },
        {
          title: '填报人电话',
          align: 'center',
          minWidth: 100,
          key: 'phone',
        },
        {
          title: '备注',
          width: 150,
          align: 'center',
          key: 'notes',
          tooltip: true
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 200,
          align: 'center',
          render: (h, params) => {
              const enable = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId||this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                      ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined;
              return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.showData(params, 1);
                  }
                }
              }, '详情'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                },
                on: {
                  click: () => {
                    this.showData(params, 2);
                  }
                }
              }, '修改'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color: params.row.fillIn != '1'&& enable ?'red':'#c5c8ce',
                    pointerEvents:params.row.fillIn != '1'&& enable ?'':'none',
                },
                on: {
                  click: () => {

                    this.$Modal.confirm({
                      title: '数据删除',
                      content: '<p>确定删除该条信息</p>',
                      okText: '确认',
                      onOk: () => {
                        this.deleteData(params);
                      },
                      cancelText: '取消'
                    });

                  }
                }
              }, '删除')
            ]);
          }
        },

      ],
      ruleCustom: {
        emName: [
          {required: true, message: '  ', trigger: 'blur'}
        ],
        companyId: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        phone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.form1datacopy.phone))) {
              callback(' ');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],

      },
      add: false,
      model1: false,
      buttonLoading: false, model2: false,
      showdata: {},

      form1datacopy: {},
      files: [],
      tableHeight: 10,
      loading: false,
    }
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.selectCodingSort();
    this.query();
  },
  methods: {
    setQueryOrgName(data) {
	  this.$set(this.form1, "companyName", data);
	},
    setQueryCompanyName(data) {
        this.$set(this.form1, 'companyId', data[data.length - 1])
    },
    beforeUploadOther(file) {
      this.files.push(file);
      return false;
    },
    deleteFile(index) {
      this.files.splice(index, 1);
    },
    setUserName(data) {
      this.form1datacopy.userName = data;
    },
    setUserId(data) {
      this.form1datacopy.leaderId = data[data.length - 1];
    },
    getFiles() {
      let url = this.fileUrl + '/' + this.form1datacopy.emId + '/files/measure'
      this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data
          let index = 0;
          this.uploadList.forEach(item=>{
            this.uploadListPercent[index]=0;
            this.uploadListVisible[index] = false;
            index++;
          })
        }
      })
    },
    beforeUpload(file) {
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.form1datacopy.emId + '/files/measure'
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles();
        }
      })
      return false
    },
    selectEmType(value) {
      this.form1.emTypes = value.join();
    },
    selectEventTypes(value) {
      this.form1.eventTypes = value.join();
    },
    downloadFile(guideId, file, index) {
      let url = this.fileUrl + '/file/' + file.id;
      let _this = this;
      this.uploadListVisible[index] = true;
      this.$http.get(url, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        progress: function (e) {
          _this.$set(_this.uploadListPercent, index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },

    remove1(id) {
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles()
      })
    },
    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    batDelete() {

    },
    deleteData(params) {
      let url = Api.deleteEmergencyMeasure;
      this.$http.delete(url + '/' + params.row.emId, {params: {}}).then((res) => {
        if (res.data.status === 200) {
          this.$Message.success('成功');
          this.query()
        } else if (res.data.status === 201) {
          this.$Message.error(res.data.msg);

        }
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    addInfo() {
      this.form1datacopy = {
        emId: this.get_uuid(),
        releaseDate: new Date(),
        twoLevelOrgId:this.currentUser.twoLevelOrgId,
        twoLevelOrgName:this.currentUser.twoLevelOrgName,

        phone:this.currentUser.mobileNumber,
        createUserName:this.currentUser.userName,
      };
      this.uploadList = [];
      this.model1 = true;
      this.add = true;
    },
    cascaderDomIdChangeHandle(data, idField) {
      if (data && data instanceof Array && data.length > 0 && idField) {
        this.$set(this.form1datacopy, idField, data[data.length - 1])
      }
    },
    cascaderDomNameChangeHandle(data, idField) {
      if (data && idField) {
        this.$set(this.form1datacopy, idField, data)
      }
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    selectCodingSort() {
      this.$http.get(Api.queryCodeDetailBySortId + '/PL-000001', {params: {}}).then((res) => {
        this.emLevelList = res.data.data;
        this.codingSortList = this.codingSortList.concat(this.emLevelList);
      });
      this.$http.get(Api.queryCodeDetailBySortId + '/ET-000001', {params: {}}).then((res) => {
        this.eventTypeList = res.data.data;
        this.codingSortList = this.codingSortList.concat(this.eventTypeList);
      });
      this.$http.get(Api.queryCodeDetailBySortId + '/PL-000010', {params: {}}).then((res) => {
        this.emTypeList = res.data.data;
        this.codingSortList = this.codingSortList.concat(this.emTypeList);
      });
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 44;
      } else {
        this.tableHeight = this.tableHeight - 44;
      }
    },
    reset() {
      if (this.$refs.queryOrgCascader) {
        this.$refs.queryOrgCascader.resetCurrentOrg();
      }
      this.form1 = {};
      this.pagedata.currentPage = 1;
      this.query();
    },
    query() {
      this.loading = true;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        orgId: sessionStorage('userId').getObject('userId').companyId,
        type: this.$route.query.id
      };
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

      let url = Api.queryEmergencyMeasure;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    showData(data, flag) {
      if (flag == 1) {
        //查看页面
        this.form1datacopy = data.row;
        this.getFiles();
        this.form1datacopy.emLevelName = this.getCodingSortName(this.form1datacopy.emLevelId)
        this.form1datacopy.eventTypeName = this.getCodingSortName(this.form1datacopy.eventTypeId)
        this.form1datacopy.emTypeName = this.getCodingSortName(this.form1datacopy.emType)
        this.form1datacopy.releaseDate = this.formatDate(new Date(this.form1datacopy.releaseDate), 'yyyy-MM-dd');
        this.model2 = true;
      } else {
        //修改页面
        this.add = false;
        // this.form1datacopy.purchaseDate = this.formatDate(new Date(this.showdata.purchaseDate), 'yyyy-MM-dd');
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        this.getFiles();
        this.model1 = true;
      }
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },

    async upload() {

    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      return a;
    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          this.form1datacopy.releaseDate = this.formatDate(new Date(this.form1datacopy.releaseDate), 'yyyy-MM-dd');
          let userId = sessionStorage('userId').getObject('userId').userId;
          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
          this.form1datacopy.emeType = this.$route.query.id;
          if (this.add) {
            this.form1datacopy.createUserId = userId;
            this.form1datacopy.createOrgId = orgId;
            this.$http.post(Api.saveEmergencyMeasure, this.form1datacopy).then((res) => {
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.query()

              } else if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
                this.model1 = false;
              }
              this.buttonLoading = false
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          } else {
            this.form1datacopy.updateUserId = userId;
            this.form1datacopy.updateOrgId = orgId;
            this.$http.post(Api.updateEmergencyMeasure, this.form1datacopy).then((res) => {
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.query()

              } else if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
                this.model1 = false;
              }
              this.buttonLoading = false
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          }


        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },

    getCodingSortName(codingCodeId) {
      let codingName = ''
      try {
        this.codingSortList.forEach(function (e) {
          if (codingCodeId == e.codingCodeId) {
            codingName = e.codingName
            throw Error();
          }
        });
      } catch (e) {
      }
      return codingName;
    }
  },
}
</script>

<style lang='css' scoped>
@import '../../../../index.css';
</style>
